const mongoose = require('mongoose');
const Product = require('../models/product.models');

exports.create = function(req,res,next){
    // console.log(req.body);//{name:'111}
    var product = new Product(req.body);
    product.save().then((data)=>{
      res.json(data);//在postman中下面出现对象
    })
}
exports.update = function(req,res,next){
    const id = req.params.id;
    console.log(id);
    Product.findByIdAndUpdate(id,{$set:req.body}).then(data=>{
        res.json(data);
    })
}
exports.remove = function(req,res,next){
    const id = req.params.id;
    console.log(id);
    Product.findByIdAndRemove(id,(err,data)=>{
        res.json(data);
    })
}
exports.list = function(req,res,next){
    // User.find().then(data=>{
    //     res.json(data);
    // })
    var page = req.body.page?req.body.page:1;
    var rows = req.body.rows?req.body.rows:5;
    var queryCondition = {};
    var cateId = req.body.cateId;
    if (cateId === undefined) {
        res.json({ message: 'error message' });
        return;
    } else {
        cateId = req.body.cateId;
        queryCondition = {
            cateId: cateId
        }
    }
    if(req.body.name&&req.body.name.trim().length>0){
        name=req.body.name;
        queryCondition = {
            "name":new RegExp(name,'i')
        };
    }
    Product.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {//+是把limit的值字符串变为数字ES6
        result.rows = result.docs;
        delete result.docs;
        res.json(result)
      });
}
exports.get = function(req,res,next){
    const id = req.params.id;
    Product.findById(id).then(data=>{
        res.json(data);
    })
    // User.findById(id,data=>{
    //     res.json(data);
    // })
}